<?php

namespace Wechat\Controller;

use Think\Controller;

class CommonController extends Controller {

    protected $customer;

    function _initialize() {

 //       cookie("openid", "otBeowu8bYi2HBRTMBWSIWzzkkbo");   //张吉煊 3
//        cookie("openid", "otBeowlAfkwtcoHunTHTDVQucZ_E");   //刘光宗 4
//        cookie("openid", "otBeowv0VZQORekZps57qRBc5d_0");   //安静 5
//        cookie("openid", "otBeowoAySKJyx16T_ZLOHao6SSQ");   //王庆 257
//        cookie("openid", "otBeownpb51w0VUpMpWT8wpwys1w");   //李明 1314
//        cookie("openid", "otBeowuIL6V1-pFyHBbEzkuTOAz0");   //胡章 328


        $callback = 'http://'.$_SERVER['HTTP_HOST']
            .$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        $callback = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

        $str = urlencode($callback);

        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
            . C('appid') . '&redirect_uri=' . C('oauthServerUrl')
            .'&response_type=code&scope=snsapi_userinfo&state='
            . $str . '&connect_redirect=1#wechat_redirect';

        $openid = cookie("openid");

        if(isNullOrEmpty($openid)) {
            header("Location: $url");
            exit();
        }

        $currentCustomer = D("Customer")
            ->queryByMap(array("openid"=>$openid));

        if(isNullOrEmpty($currentCustomer)) {

            $currentCustomer = D("Customer")
                ->queryByMap(array("openid"=>$openid));
            if(isNullOrEmpty($currentCustomer)) {
                header("Location: $url");
                exit();
            }

            if($currentCustomer["openid"] != $openid) {
                cookie("openid", null);
                cookie("openid", $currentCustomer["openid"]);
            }

        }

        $this->customer = $currentCustomer;

    }

    /**
     * 	作用：生成签名
     */
    protected function getSign($Obj) {

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }

    /**
     * 	作用：array转xml
     */
    protected function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml.="<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml.="<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml.="</xml>";
        return $xml;
    }

    protected function signature() {
        $Obj['jsapi_ticket'] = jsapi_ticket();
        $Obj['noncestr'] = createNoncestr();
        $Obj['url'] = "http://" . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
        $Obj['timestamp'] = time();

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        //dump($Parameters);
        $String = formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        //$String = $String."&key=".C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = sha1($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        //$Obj['signature'] = strtoupper($String);
        $Obj['signature'] = $String;

        return $Obj;
    }

    /**
     * 	作用：产生随机字符串，不长于32位
     */
    protected function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str.= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 	作用：格式化参数，签名过程需要使用
     */
    protected function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /**
     * 	作用：将xml转为array
     */
    protected function xmlToArray($xml) {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

}